<?php
/**
* 
*/
class DocumentsController extends AppController
{
	var $name = 'Documents';
//	var $scaffold;
	var $components = array('UserAuth', 'ContentRight', 'RequestHandler');
	var $helpers = array('Html', 'Number', 'Form', 'Javascript', 'Ajax');
	var $uses = array('Document', 'User', 'Ticket');
	
	public function beforeFilter()
	{
		if ($this->action != 'add' && $this->action != 'edit') {
			$this->set('project_id', $this->params['projectId']);
			$this->set('project_name', $this->params['projectName']);			
		} else {
			$this->set('project_id', 0);
			$this->set('project_name', "");
		}
		if ($this->RequestHandler->isAjax()) {
	        $db =& ConnectionManager::getDataSource('default');
	        $db->fullDebug = false;
	    }
	}
	
	/**
	 * Private method to have the extention of the file.
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	private function getFileExtension($str) {
        $i = strrpos($str, ".");
        if (!$i) { return ""; }
        $l = strlen($str) - $i;
        $ext = substr($str,$i+1,$l);
		$exttbl = array('abw', 'ai', 'aiff', 'asf', 'avi', 'bin', 'blend', 'bmp', 'bz2', 'c', 'css', 'csv', 'deb', 'djvu', 'doc', 'docx', 'dvi', 'eps', 'flv', 'gif', 'gz', 'h', 'html', 'jpg', 'js', 'kml', 'kmz', 'mid', 'mka', 'mkv', 'mng', 'mov', 'mp3', 'mp4', 'mpg', 'odb', 'odc', 'odf', 'odg', 'odi', 'odm', 'odp', 'ods', 'odt', 'ogg', 'otg', 'otp', 'ots', 'ott', 'pas', 'pdf', 'pgn', 'png', 'pps', 'ppt', 'pptx', 'ps', 'psd', 'qt', 'ra', 'ram', 'rm', 'rpm', 'rtf', 'sdd', 'sdw', 'sit', 'smil', 'svg', 'swf', 'sxc', 'sxi', 'sxw', 'tex', 'tgz', 'tif', 'torrent', 'ttf', 'txt', 'wav', 'wmv', 'xcf', 'xls', 'xml', 'zip');
		if (in_array($ext, $exttbl))
        	return $ext;
		else
			return 'defaut';
    }
	
	/**
	 * Private method for cleaning filemane.
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	private function cleanFileName($str) {
        $i = strrpos($str, "/");
		if ($i) {
			$l = strlen($str) - $i;
        	$str = substr($str,$i+1,$l);
		}
		$i = strrpos($str, "\\");
		if ($i) {
			$l = strlen($str) - $i;
        	$str = substr($str,$i+1,$l);
		}
		$i = strrpos($str, ".");
        if ($i)
			$name = substr($str, 0, $i);
		else
			$name = $str;
		$name = str_replace('_', ' ', $name);
		$name = str_replace('-', ' ', $name);
		$name = ucfirst(strtolower(trim($name)));
        return $name;
    }
	
	/**
	 * Home page of project documents.
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	public function index()
	{
		$project_id = $this->params['projectId'];
		if ($project_id != null) {
			$this->UserAuth->checkPermission($project_id);
		 	$results = $this->Document->findAllByProjectId($project_id, NULL, 'Document.update_date DESC');
			$this->set ('object', $results);
			$this->set ('allowDelete' ,$this->UserAuth->checkAcces($this->params['projectId'], 'project_document_del'));
			$user = $this->UserAuth->getUser();
			$this->set ('user_id' ,$user['id']);
		}
	}
	
	/**
	 * Project documents by letter.
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	public function byletter()
	{
		$project_id = $this->params['projectId'];
		if ($project_id != null) {
			$this->UserAuth->checkPermission($project_id);
		 	$results = $this->Document->findAllByProjectId($project_id, NULL, 'Document.name ASC');
			$this->set ('object', $results);
			$this->set ('allowDelete' ,$this->UserAuth->checkAcces($this->params['projectId'], 'project_document_del'));
			$user = $this->UserAuth->getUser();
			$this->set ('user_id' ,$user['id']);
		}
	}
	
	/**
	 * Add a new document (this is a method without a view)
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	public function add()
	{
		if ($this->UserAuth->checkAcces($this->data['Document']['project_id'], 'project_document_add') || $this->data['Document']['ticket_id']) {
			if (empty($this->data) == false && is_uploaded_file($this->data['Document']['File']['tmp_name'])) {
				if ($this->data['Document']['File']['size'] > 2048 * 1024) {
					$this->Session->setFlash('Failure, file too big.');
					$this->redirect ('/' . $this->data['Document']['project_name'] . '/' . $this->data['Document']['project_id'] . '/documents/');
				} else {
					$fileData = fread(fopen($this->data['Document']['File']['tmp_name'], "r"), $this->data['Document']['File']['size']+1024);
					$this->data['Document']['file_name'] = $this->data['Document']['File']['name'];
					if ($this->data['Document']['name'] == '')
						$this->data['Document']['name'] = $this->cleanFileName($this->data['Document']['File']['name']);
					$this->data['Document']['size'] = $this->data['Document']['File']['size'];
					$this->data['Document']['extention'] = $this->getFileExtension($this->data['Document']['File']['name']);
					$this->data['Document']['creation_date'] = date("Y-m-d H:i:s");
					$this->data['Document']['update_date'] = date("Y-m-d H:i:s");
					$this->data['Document']['user_id'] = $this->viewVars['user']['id'];
					if ($this->Document->save($this->data['Document']))
					{
						$id = $this->Document->getLastInsertId();
						$this->Session->setFlash('File saved.');
						$this->Document->saveContent($fileData);
						if ($this->data['Document']['ticket_id'])
							$this->redirect ('/' . $this->data['Document']['project_name'] . '/' . $this->data['Document']['project_id'] . '/tickets/view/'.$this->data['Document']['ticket_id'].'/');
						else
							$this->redirect ('/' . $this->data['Document']['project_name'] . '/' . $this->data['Document']['project_id'] . '/documents/');
					}
				}			
			} else {
				$this->Session->setFlash('Failure, file not saved.');
				if ($this->data['Document']['ticket_id'])
					$this->redirect ('/' . $this->data['Document']['project_name'] . '/' . $this->data['Document']['project_id'] . '/tickets/view/'.$this->data['Document']['ticket_id'].'/');
				else
					$this->redirect ('/' . $this->data['Document']['project_name'] . '/' . $this->data['Document']['project_id'] . '/documents/');
			}
		} else {
				$this->Session->setFlash('Failure, you don\'t have the right to add a file.');
				$this->redirect ('/' . $this->data['Document']['project_name'] . '/' . $this->data['Document']['project_id'] . '/documents/');
		}
	}

	/**
	 * Delete a document (this is a method without a view)
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	function del($id)
	{
		$this->Document->id = $id;
		$results = $this->Document->read();
		if(empty($this->data))
			$this->data['Document'] = $results['Document'];
		$user = $this->UserAuth->getUser();
		$redir = '/' . $results[0]['Project']['rewrite_name'] . '/' . $results[0]['Project']['id'] . '/documents/';
		if ($this->UserAuth->checkAcces($this->data['Document']['project_id'], 'project_document_del') || $this->data['Document']['user_id']  == $user_id) {
			if ($this->Document->del($id, false)) {
				$this->Document->deleteContent($id);
				$this->Session->setFlash('File deleted.');
			} else {
				$this->Session->setFlash("Problem : The file can't deleted");
			}
		} else {
			$this->Session->setFlash("You don't have the right to del this file");
		}
		$this->redirect ($redir);
	}

	/**
	 * Edit a document
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	function edit($id)
	{
		$this->Document->id = $id;
		$results = $this->Document->read();
		$user = $this->UserAuth->getUser();
		if(empty($this->data)) {
			$this->data['Document'] = $results['Document'];
			$this->set ('project_id', $results['Project']['id']);
			$this->set ('project_name', $results['Project']['name']);
		} else {
			
			if ($this->UserAuth->checkAcces($this->data['Document']['project_id'], 'project_document_del') || $this->data['Document']['user_id']  == $user_id) {
				if ($this->Document->save($this->data['Document'])) {
					$this->Session->setFlash("File information updated", true);
					$this->redirect ('/' . $this->data['Document']['project_name'] . '/' . $this->data['Document']['project_id'] . '/documents/');
				}
			}else{
				$this->Session->setFlash('Failure, you don\'t have the right to edit a file.');
				$this->redirect ('/' . $this->params['projectName'] . '/' . $this->params['projectId'] . '/documents/');
			}
		}
	}

	/**
	 * Download a document (this is a method without a view)
	 *
	 * @return void
	 * @author Arnaud Vuillaume
	 **/
	function download($id)
	{
		$this->Document->id = $id;
		$results = $this->Document->read();
		header('Content-type: ' . $results['Document']['type']);
		header('Content-length: ' . $results['Document']['size']);
		header('Content-Disposition: attachment; filename="'.$results['Document']['file_name'].'"');
		echo $this->Document->loadContent($id);
		exit();	
	}

}

?>